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

# Unsloth 2x schnelleres Fine-Tuning

Unsloth schreibt die leistungs‑kritischen Teile von HuggingFace Transformers mit handoptimierten Triton‑Kernels neu und liefert **2x schnellere Trainingsgeschwindigkeit** und **70% weniger VRAM** ohne Genauigkeitsverlust. Es ist ein Drop‑in‑Ersatz — Ihre bestehenden TRL/PEFT‑Skripte funktionieren unverändert nach dem Austausch des Imports.

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

## Hauptmerkmale

* **2x schnelleres Training** — benutzerdefinierte Triton‑Kernels für Attention, RoPE, Kreuzentropie und RMS‑Norm
* **70% weniger VRAM** — intelligente Gradient‑Checkpointing und speicherabbildbare Gewichte
* **Drop‑in Ersatz für HuggingFace** — nur ein Importwechsel, nichts weiter
* **QLoRA / LoRA / vollständiges Fine‑Tuning** — alle Modi werden sofort unterstützt
* **Native Exportfunktion** — direkt in GGUF (alle Quantisierungstypen), LoRA‑Adapter oder zusammengeführtes 16‑Bit speichern
* **Breite Modellunterstützung** — Llama 3.x, Mistral, Qwen 2.5, Gemma 2, DeepSeek‑R1, Phi‑4 und mehr
* **Kostenlos und Open Source** (Apache 2.0)

## Anforderungen

| Komponente | Minimum        | Empfohlen      |
| ---------- | -------------- | -------------- |
| GPU        | RTX 3060 12 GB | RTX 4090 24 GB |
| VRAM       | 10 GB          | 24 GB          |
| RAM        | 16 GB          | 32 GB          |
| Festplatte | 40 GB          | 80 GB          |
| CUDA       | 11.8           | 12.1+          |
| Python     | 3.10           | 3.11           |

**Clore.ai-Preise:** RTX 4090 ≈ $0.5–2/Tag · RTX 3090 ≈ $0.3–1/Tag · RTX 3060 ≈ $0.15–0.3/Tag

Ein 7B‑Modell mit 4‑Bit‑QLoRA passt in **\~10 GB VRAM**, wodurch sogar eine RTX 3060 nutzbar wird.

## Schnellstart

### 1. Unsloth installieren

```bash
# Erstelle ein venv (empfohlen)
python -m venv /workspace/unsloth-env
source /workspace/unsloth-env/bin/activate

pip install --upgrade pip
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes xformers
```

### 2. Ein Modell mit 4‑Bit‑Quantisierung laden

```python
from unsloth import FastLanguageModel
import torch

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
    max_seq_length=2048,
    dtype=None,            # automatische Erkennung (float16 auf Ampere, bfloat16 auf Ada)
    load_in_4bit=True,
)
```

### 3. LoRA‑Adapter anwenden

```python
model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                     "gate_proj", "up_proj", "down_proj"],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",   # 70% VRAM‑Einsparung
    random_state=42,
    use_rslora=False,
    loftq_config=None,
)
```

### 4. Daten vorbereiten und trainieren

```python
from datasets import load_dataset
from trl import SFTTrainer
from transformers import TrainingArguments

dataset = load_dataset("yahma/alpaca-cleaned", split="train")

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset,
    dataset_text_field="text",
    max_seq_length=2048,
    dataset_num_proc=2,
    packing=True,
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=10,
        num_train_epochs=1,
        learning_rate=2e-4,
        fp16=not torch.cuda.is_bf16_supported(),
        bf16=torch.cuda.is_bf16_supported(),
        logging_steps=10,
        optim="adamw_8bit",
        weight_decay=0.01,
        lr_scheduler_type="linear",
        seed=42,
        output_dir="/workspace/outputs",
    ),
)

stats = trainer.train()
print(f"Training loss: {stats.training_loss:.4f}")
```

## Modell exportieren

### Nur LoRA‑Adapter speichern

```python
model.save_pretrained("/workspace/lora-adapter")
tokenizer.save_pretrained("/workspace/lora-adapter")
```

### Vollständiges Modell zusammenführen und speichern (float16)

```python
model.save_pretrained_merged(
    "/workspace/merged-model",
    tokenizer,
    save_method="merged_16bit",
)
```

### Export nach GGUF für Ollama / llama.cpp

```python
# Quantisiere zu Q4_K_M (guter Kompromiss zwischen Größe und Qualität)
model.save_pretrained_gguf(
    "/workspace/gguf-output",
    tokenizer,
    quantization_method="q4_k_m",
)

# Andere Optionen: q5_k_m, q8_0, f16
```

Nach dem Export mit Ollama bereitstellen:

```bash
# Erstelle eine Ollama Modelfile
cat > Modelfile <<EOF
FROM /workspace/gguf-output/unsloth.Q4_K_M.gguf
TEMPLATE "{{ .System }}\n{{ .Prompt }}"
PARAMETER temperature 0.7
EOF

ollama create my-finetuned -f Modelfile
ollama run my-finetuned "Fasse die wichtigsten Punkte der Transformers‑Architektur zusammen"
```

## Beispielanwendungen

### Feinabstimmung auf einem eigenen Chat‑Datensatz

```python
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(tokenizer, chat_template="llama-3.1")

def format_chat(example):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": example["instruction"]},
        {"role": "assistant", "content": example["output"]},
    ]
    return {"text": tokenizer.apply_chat_template(messages, tokenize=False)}

dataset = dataset.map(format_chat)
```

### DPO / ORPO Alignment Training

```python
from trl import DPOTrainer, DPOConfig

dpo_trainer = DPOTrainer(
    model=model,
    ref_model=None,          # Unsloth verwaltet das Referenzmodell intern
    args=DPOConfig(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        learning_rate=5e-6,
        num_train_epochs=1,
        beta=0.1,
        output_dir="/workspace/dpo-output",
    ),
    train_dataset=dpo_dataset,
    tokenizer=tokenizer,
)
dpo_trainer.train()
```

## VRAM-Nutzungsreferenz

| Modell         | Quant  | Methode | VRAM    | GPU         |
| -------------- | ------ | ------- | ------- | ----------- |
| Llama 3.1 8B   | 4‑Bit  | QLoRA   | \~10 GB | RTX 3060    |
| Llama 3.1 8B   | 16‑Bit | LoRA    | \~18 GB | RTX 3090    |
| Qwen 2.5 14B   | 4‑Bit  | QLoRA   | \~14 GB | RTX 3090    |
| Mistral 7B     | 4‑Bit  | QLoRA   | \~9 GB  | RTX 3060    |
| DeepSeek-R1 7B | 4‑Bit  | QLoRA   | \~10 GB | RTX 3060    |
| Llama 3.3 70B  | 4‑Bit  | QLoRA   | \~44 GB | 2× RTX 3090 |

## Tipps

* **Immer verwenden `use_gradient_checkpointing="unsloth"`** — dies ist der größte einzelne VRAM‑Sparer, einzigartig bei Unsloth
* **Setze `lora_dropout=0`** — Unsloths Triton‑Kernels sind für Null‑Dropout optimiert und laufen schneller
* **Verwenden Sie `packing=True`** im SFTTrainer, um Padding‑Verschwendung bei kurzen Beispielen zu vermeiden
* **Beginnen Sie mit `r=16`** für LoRA‑Rang — auf 32 oder 64 nur erhöhen, wenn der Validierungsverlust stagniert
* **Mit wandb überwachen** — füge hinzu `report_to="wandb"` in TrainingArguments zur Verlustüberwachung
* **Batch-Größen-Tuning** — erhöhe `per_device_train_batch_size` bis du an die VRAM‑Grenze kommst, kompensiere dann mit `gradient_accumulation_steps`

## Fehlerbehebung

| Problem                                  | Lösung                                                                                          |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `OutOfMemoryError` während des Trainings | Batch‑Größe auf 1 reduzieren, `max_seq_length`, oder 4‑Bit‑Quantisierung verwenden              |
| Triton‑Kernel‑Kompilierungsfehler        | Ausführen `pip install triton --upgrade` und sicherstellen, dass das CUDA‑Toolkit übereinstimmt |
| Langsamer erster Schritt (Kompilierung)  | Normal — Triton kompiliert die Kernels beim ersten Lauf, danach werden sie gecacht              |
| `bitsandbytes` CUDA‑Versionsfehler       | Installiere die passende Version: `pip install bitsandbytes --upgrade`                          |
| Verlustspitzen während des Trainings     | Lernrate auf 1e-4 senken, Warmup‑Schritte hinzufügen                                            |
| GGUF‑Export stürzt ab                    | Stelle genügend RAM (2× Modellgröße) und Festplattenspeicher für die Konvertierung sicher       |

## Ressourcen

* [Unsloth GitHub](https://github.com/unslothai/unsloth)
* [Unsloth Wiki — Alle Notebooks](https://github.com/unslothai/unsloth/wiki)
* [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/unsloth-finetune.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.
