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

# LitGPT

**LitGPT** ist eine leistungsstarke Bibliothek zum Vortrainieren, Feinabstimmen und Bereitstellen von über 20 großen Sprachmodellen, aufgebaut auf PyTorch Lightning. Mit über 12.000 GitHub-Sternen ist sie ein bevorzugtes Toolkit für Ingenieure, die sauberen, leicht anpassbaren LLM-Trainingscode ohne den Abstraktionsaufwand von HuggingFace Transformers benötigen.

Jedes Modell in LitGPT ist \~1.000 Zeilen sauberes PyTorch — keine Vererbungsketten mit 10 Ebenen, keine Magie. Du kannst die Llama-3-Implementierung an einem Nachmittag vollständig lesen und sie dann mit Gewissheit ändern.

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

***

## Was ist LitGPT?

LitGPT bietet produktionsreife Implementierungen modernster LLMs mit einer einheitlichen Trainingsschnittstelle:

* **Über 20 unterstützte Modelle** — Llama 3, Gemma 2, Mistral, Phi-3, Falcon, StableLM und mehr
* **Vortraining von Grund auf** — vollständiges Vortraining mit Flash Attention, FSDP und Gradient Checkpointing
* **Effizientes Feinabstimmen** — vollständiges Finetuning, LoRA, QLoRA und Adapter-Methoden
* **Bereitstellung mit Vertrauen** — integrierter Inferenzserver mit Quantisierung
* **Multi-GPU-Unterstützung** — DDP, FSDP, Tensorparallelität sofort einsatzbereit
* **Speichereffizient** — 4-Bit-Quantisierung, Gradient Checkpointing, Aktivierungs-Checkpointing

***

## Serveranforderungen

| Komponente     | Minimum          | Empfohlen                |
| -------------- | ---------------- | ------------------------ |
| GPU            | RTX 3090 (24 GB) | A100 80 GB / H100        |
| VRAM           | 16 GB (7B LoRA)  | 80 GB+ (70B vollständig) |
| RAM            | 32 GB            | 64 GB+                   |
| CPU            | 8 Kerne          | 16+ Kerne                |
| Speicher       | 100 GB           | 500 GB+                  |
| Betriebssystem | Ubuntu 20.04+    | Ubuntu 22.04             |
| Python         | 3.10+            | 3.11                     |
| CUDA           | 11.8+            | 12.1+                    |

### VRAM-Anforderungen nach Aufgabe

| Aufgabe           | Modell      | VRAM              |
| ----------------- | ----------- | ----------------- |
| Inference (4-Bit) | Llama-3 8B  | \~6 GB            |
| LoRA-Finetune     | Llama-3 8B  | \~16 GB           |
| Volles Finetuning | Llama-3 8B  | \~80 GB           |
| LoRA-Finetune     | Llama-3 70B | \~48 GB (2×A100)  |
| Volles Finetuning | Llama-3 70B | \~640 GB (8×A100) |
| QLoRA-Finetune    | Llama-3 8B  | \~8 GB            |

***

## Ports

| Port | Dienst                  | Hinweise                          |
| ---- | ----------------------- | --------------------------------- |
| 22   | SSH                     | Terminalzugang & Dateitransfer    |
| 8000 | LitGPT Inference Server | REST-API für Modellbereitstellung |

***

## Schnellstart mit Docker

```bash
# Ziehe das offizielle LitGPT-Image
docker pull pytorchlightning/litgpt:latest

# Starte interaktiven Container mit GPU
docker run -it --gpus all \
  -p 8000:8000 \
  -v $(pwd)/checkpoints:/checkpoints \
  -v $(pwd)/data:/data \
  pytorchlightning/litgpt:latest \
  bash

# Oder führe einen bestimmten Befehl direkt aus
docker run --gpus all \
  -v $(pwd)/checkpoints:/checkpoints \
  pytorchlightning/litgpt:latest \
  litgpt download --repo_id meta-llama/Llama-3.2-3B-Instruct
```

***

## Installation auf Clore.ai

### Schritt 1 — Einen Server mieten

1. Gehe zu [Clore.ai Marketplace](https://clore.ai/marketplace)
2. Filtere nach **VRAM ≥ 24 GB** (RTX 3090 oder besser)
3. Wähle ein **PyTorch** oder **CUDA 12.1** Basis-Image
4. Öffne Ports **22** und **8000** in deinen Bestelloptionen
5. Wähle **Speicher ≥ 200 GB** für Modellgewichte

### Schritt 2 — Verbindung per SSH

```bash
ssh root@<server-ip> -p <ssh-port>
```

### Schritt 3 — LitGPT installieren

```bash
# Installation via pip (empfohlen)
pip install litgpt

# Mit allen Extras (Quantisierung, Server, etc.)
pip install 'litgpt[all]'

# Oder von der Quelle installieren für neueste Funktionen
git clone https://github.com/Lightning-AI/litgpt.git
cd litgpt
pip install -e '.[all]'
```

### Schritt 4 — Installation überprüfen

```bash
litgpt --help
```

Erwartete Ausgabe:

```
Verwendung: litgpt [OPTIONS] COMMAND [ARGS]...
  
Befehle:
  chat       Chat mit einem Modell
  convert    Modellgewichte konvertieren
  download   Modellgewichte herunterladen
  evaluate   Ein Modell bewerten
  finetune   Ein Modell feinabstimmen
  generate   Text generieren
  pretrain   Ein Modell vortrainieren
  serve      Ein Modell für Inferenz bereitstellen
```

***

## Modelle herunterladen

LitGPT lädt Modelle von Hugging Face herunter:

```bash
# Liste verfügbare Modelle auf
litgpt download --list

# Lade Llama 3.2 3B herunter (benötigt HF-Token für geschützte Modelle)
litgpt download \
  --repo_id meta-llama/Llama-3.2-3B-Instruct \
  --checkpoint_dir checkpoints/

# Lade Mistral 7B herunter (offener Zugang)
litgpt download \
  --repo_id mistralai/Mistral-7B-Instruct-v0.3

# Lade Gemma 2 2B herunter
litgpt download \
  --repo_id google/gemma-2-2b-it \
  --access_token dein-hf-token

# Lade Phi-3 herunter (klein aber leistungsstark)
litgpt download \
  --repo_id microsoft/Phi-3-mini-4k-instruct
```

### HuggingFace-Token setzen

```bash
# Für geschützte Modelle (Llama, Gemma)
export HF_TOKEN=hf_dein-token-hier

# Oder per CLI authentifizieren
pip install huggingface_hub
huggingface-cli login
```

***

## Inference (Chat & Generieren)

```bash
# Interaktiver Chat
litgpt chat \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct

# Einzelne Generierung
litgpt generate \
  --prompt "Erkläre GPU-Computing in einfachen Worten" \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --max_new_tokens 200

# Mit Temperatur und Sampling
litgpt generate \
  --prompt "Schreibe eine Python-Funktion, um eine Liste zu sortieren" \
  --checkpoint_dir checkpoints/mistralai/Mistral-7B-Instruct-v0.3 \
  --temperature 0.7 \
  --top_p 0.9 \
  --max_new_tokens 500
```

***

## Feinabstimmung

### LoRA-Finetuning (empfohlen)

LoRA trainiert eine kleine Menge Adapter-Parameter (typischerweise 0,1–1 % der Gesamtgewichte), während das Basismodell eingefroren bleibt. Llama 3 8B LoRA auf 10K Beispielen dauert \~2 Stunden auf einer RTX 3090 mit `r=16`.

```bash
# Bereite dein Dataset vor
# Format: JSON Lines mit {"instruction": "...", "input": "...", "output": "..."}
cat > data/train.json << 'EOF'
{"instruction": "Was ist GPU-Cloud-Computing?", "input": "", "output": "GPU-Cloud-Computing bietet bedarfsgerechten Zugriff auf GPU-Hardware über das Internet und ermöglicht KI-Training und -Inference ohne eigenen physischen Hardwarebesitz."}
{"instruction": "Wie miete ich eine GPU auf Clore.ai?", "input": "", "output": "Besuche clore.ai/marketplace, filtere nach GPU-Spezifikationen, wähle einen Server, konfiguriere Ports und klicke auf mieten. SSH-Zugang wird sofort bereitgestellt."}
EOF

# Finetune mit LoRA
litgpt finetune lora \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --data JSON \
  --data.json_path data/train.json \
  --train.epochs 3 \
  --train.micro_batch_size 4 \
  --lora_r 8 \
  --lora_alpha 16 \
  --out_dir out/llama-lora-finetuned

# Training überwachen
# LitGPT gibt Logs mit Verlust, Lernrate und ETA aus
```

### QLoRA (4-Bit + LoRA)

Verwende QLoRA, um große Modelle mit begrenztem VRAM zu finetunen. Llama 3 8B passt auf eine einzelne RTX 3090 mit 24 GB:

```bash
litgpt finetune lora \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-8B-Instruct \
  --quantize bnb.nf4 \
  --train.epochs 3 \
  --train.micro_batch_size 2 \
  --lora_r 16 \
  --lora_alpha 32 \
  --out_dir out/llama-qlora
```

### Vollständiges Finetuning

```bash
litgpt finetune full \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --data JSON \
  --data.json_path data/train.json \
  --train.epochs 2 \
  --train.micro_batch_size 2 \
  --train.accumulate_gradients 8 \
  --out_dir out/llama-full-finetuned
```

### Multi-GPU-Training

```bash
# Verwende FSDP über mehrere GPUs
litgpt finetune full \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-8B-Instruct \
  --devices 4 \
  --strategy fsdp \
  --train.epochs 3 \
  --out_dir out/llama-multigpu
```

***

## Modelle bereitstellen (REST-API)

```bash
# Inferenzserver starten
litgpt serve \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --host 0.0.0.0 \
  --port 8000

# Die API testen
curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Was ist die Hauptstadt von Frankreich?",
    "max_new_tokens": 100,
    "temperature": 0.7
  }'
```

### Python-Client

```python
import requests

response = requests.post(
    "http://<server-ip>:8000/predict",
    json={
        "prompt": "Erkläre Reinforcement Learning",
        "max_new_tokens": 500,
        "temperature": 0.8,
        "top_p": 0.9,
    }
)
print(response.json()["output"])
```

***

## Vortraining von Grund auf

Zum Trainieren eines eigenen LLM von Grund auf mit deinen Daten:

```bash
# Bereite Pretraining-Daten vor (tokenisiert und in Chunks)
python scripts/prepare_redpajama.py \
  --source_path /data/raw_text \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --destination_path /data/tokenized

# Starte Vortraining
litgpt pretrain \
  --model_name Llama-3.2 \
  --data /data/tokenized \
  --train.micro_batch_size 4 \
  --train.max_tokens 10_000_000_000 \
  --devices 8 \
  --strategy fsdp \
  --out_dir out/my-pretrained-llm
```

***

## Modelle konvertieren und exportieren

```bash
# LoRA-Gewichte in das Basismodell mergen
litgpt merge_lora \
  --checkpoint_dir out/llama-lora-finetuned

# In HuggingFace-Format konvertieren für Verteilung
litgpt convert to_hf \
  --checkpoint_dir out/llama-lora-finetuned/final \
  --output_dir hf_model/

# In GGUF-Format exportieren (für Ollama/LlamaCpp)
# Nach HF-Export das Konvertierungsskript von llama.cpp verwenden
python llama.cpp/convert.py hf_model/ --outfile model.gguf
```

***

## Modelle evaluieren

```bash
# Führe MMLU-Benchmark aus
litgpt evaluate \
  --checkpoint_dir checkpoints/meta-llama/Llama-3.2-3B-Instruct \
  --tasks mmlu \
  --num_fewshot 5

# Mehrere Benchmarks ausführen
litgpt evaluate \
  --checkpoint_dir out/llama-lora-finetuned/final \
  --tasks "mmlu,hellaswag,truthfulqa_mc"
```

***

## Clore.ai GPU-Empfehlungen

LitGPT deckt drei unterschiedliche Workloads ab — Inferenz, LoRA-Finetuning und vollständiges Vortraining — jeweils mit unterschiedlichen GPU-Anforderungen.

| Workload                                     | GPU            | VRAM  | Hinweise                                                                   |
| -------------------------------------------- | -------------- | ----- | -------------------------------------------------------------------------- |
| Inference / Chat (7–8B-Modelle)              | **RTX 3090**   | 24 GB | Passt Llama 3 8B in bf16; \~95 Tok/s Generierung                           |
| LoRA-Finetune (7–8B-Modelle)                 | **RTX 3090**   | 24 GB | Budget-Wahl; QLoRA hält den VRAM unter 10 GB                               |
| LoRA-Finetune (7–8B), schnelle Iteration     | **RTX 4090**   | 24 GB | \~35 % schneller als 3090; reduziert einen 2‑Stunden-Job auf \~1,4 Stunden |
| Volles Finetuning (7B) oder QLoRA (70B)      | **A100 40 GB** | 40 GB | 40 GB passt für 7B in voller Präzision oder 70B in 4-Bit                   |
| Volles Finetuning (13B+) oder Pretrain-Läufe | **A100 80 GB** | 80 GB | Höchste Durchsatzrate; \~2.800 Tok/s Training auf 8B                       |

**Empfohlen für die meisten Nutzer:** Paar RTX 3090 (2×24 GB = 48 GB effektiv mit FSDP). Handhabt QLoRA auf 70B-Modellen oder vollständiges Finetuning auf 7B-Modellen mit Tensor-Parallelität. Kosten auf Clore.ai: ca. $0.25/Stunde für zwei 3090.

**Für Pretraining oder Finetuning >70B:** Verwende 4×A100 80GB mit FSDP. LitGPTs FSDP-Integration übernimmt das Sharding transparent — übergib einfach `--devices 4 --strategy fsdp`.

***

## Fehlerbehebung

### CUDA Out of Memory

```bash
# Batch-Größe reduzieren
--train.micro_batch_size 1

# Gradient Checkpointing aktivieren
--train.gradient_checkpointing true

# QLoRA statt LoRA verwenden
--quantize bnb.nf4

# GPU-Speicher prüfen
nvidia-smi
```

### Download schlägt fehl / HuggingFace 401

```bash
# HF-Token setzen
export HF_TOKEN=hf_dein-token-hier
huggingface-cli login

# Oder direkt übergeben
litgpt download \
  --repo_id meta-llama/Llama-3.2-3B-Instruct \
  --access_token hf_dein-token
```

### Trainingsverlust sinkt nicht

```bash
# Überprüfe dein Datenformat — muss gültige JSON Lines sein
python -c "
import json
with open('data/train.json') as f:
    for i, line in enumerate(f):
        json.loads(line)
        if i < 3: print(f'Line {i}: OK')
print('Alle Zeilen gültig')
"

# Lernrate reduzieren
--train.lr 1e-5  # Standard ist oft zu hoch für kleine Datensätze

# Datengröße prüfen — LoRA benötigt mindestens 100–1000 Beispiele
wc -l data/train.json
```

### Server-Port 8000 nicht erreichbar

```bash
# Prüfe, ob der Server lauscht
ss -tlnp | grep 8000

# Firewall öffnen
ufw allow 8000/tcp

# Server mit explizitem Host neu starten
litgpt serve \
  --checkpoint_dir checkpoints/... \
  --host 0.0.0.0 \
  --port 8000
```

### Multi-GPU-Training hängt

```bash
# NCCL-Konnektivität prüfen
python -c "import torch; print(torch.cuda.device_count())"

# Für kleinere Modelle stattdessen DDP versuchen
--strategy ddp

# NCCL-Umgebungsvariablen setzen
export NCCL_DEBUG=INFO
export NCCL_IB_DISABLE=1  # Falls InfiniBand nicht verfügbar ist
```

***

## Nützliche Links

* **GitHub**: <https://github.com/Lightning-AI/litgpt> ⭐ 12K+
* **Dokumentation**: <https://lightning.ai/docs/litgpt>
* **PyTorch Lightning**: <https://lightning.ai>
* **HuggingFace-Modelle**: <https://huggingface.co/models>
* **Discord**: <https://discord.gg/lightning-ai>
* **Clore.ai Marketplace**: <https://clore.ai/marketplace>


---

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