# Llama.cpp Server

Führen Sie LLMs effizient mit dem llama.cpp-Server auf GPU aus.

{% 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       | 8GB           | 16GB+     |
| VRAM      | 6GB           | 8GB+      |
| Netzwerk  | 200Mbps       | 500Mbps+  |
| Startzeit | \~2-5 Minuten | -         |

{% hint style="info" %}
Llama.cpp ist speichereffizient dank GGUF-Quantisierung. 7B-Modelle können auf 6-8 GB VRAM laufen.
{% 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 Llama.cpp?

Llama.cpp ist die schnellste CPU-/GPU-Inferenz-Engine für LLMs:

* Unterstützt GGUF-quantisierte Modelle
* Geringer Speicherverbrauch
* OpenAI-kompatible API
* Mehrbenutzerunterstützung

## Quantisierungsstufen

| Format   | Größe (7B) | Geschwindigkeit | Qualität      |
| -------- | ---------- | --------------- | ------------- |
| Q2\_K    | 2,8 GB     | Am schnellsten  | Gering        |
| Q4\_K\_M | 4,1 GB     | Schnell         | Gut           |
| Q5\_K\_M | 4,8 GB     | Mittel          | Großartig     |
| Q6\_K    | 5,5 GB     | Langsamer       | Ausgezeichnet |
| Q8\_0    | 7,2 GB     | Langsamste      | Am besten     |

## Schnelle Bereitstellung

**Docker-Image:**

```
ghcr.io/ggerganov/llama.cpp:server-cuda
```

**Ports:**

```
22/tcp
8080/http
```

**Befehl:**

```bash

# Modell herunterladen
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Server starten
./llama-server \
    -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
    --host 0.0.0.0 \
    --port 8080 \
    -ngl 35 \
    -c 4096
```

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

### Überprüfen, ob es funktioniert

```bash
# Gesundheit prüfen
curl https://your-http-pub.clorecloud.net/health

# Serverinformationen abrufen
curl https://your-http-pub.clorecloud.net/props
```

{% hint style="warning" %}
Wenn Sie HTTP 502 erhalten, startet der Dienst möglicherweise noch oder lädt das Modell herunter. Warten Sie 2–5 Minuten und versuchen Sie es erneut.
{% endhint %}

## Vollständige API-Referenz

### Standardendpunkte

| Endpunkt               | Methode | Beschreibung                              |
| ---------------------- | ------- | ----------------------------------------- |
| `/health`              | GET     | Health-Check                              |
| `/v1/models`           | GET     | Modelle auflisten                         |
| `/v1/chat/completions` | POST    | Chat (OpenAI-kompatibel)                  |
| `/v1/completions`      | POST    | Textvervollständigung (OpenAI-kompatibel) |
| `/v1/embeddings`       | POST    | Embeddings erzeugen                       |
| `/completion`          | POST    | Native Completion-Endpunkt                |
| `/tokenize`            | POST    | Text tokenisieren                         |
| `/detokenize`          | POST    | Tokens detokenisieren                     |
| `/props`               | GET     | Servereigenschaften                       |
| `/metrics`             | GET     | Prometheus-Metriken                       |

#### Text tokenisieren

```bash
curl https://your-http-pub.clorecloud.net/tokenize \
    -H "Content-Type: application/json" \
    -d '{"content": "Hello world"}'
```

Antwort:

```json
{"tokens": [15496, 1917]}
```

#### Servereigenschaften

```bash
curl https://your-http-pub.clorecloud.net/props
```

Antwort:

```json
{
  "total_slots": 1,
  "chat_template": "...",
  "default_generation_settings": {...}
}
```

## Aus Quellen bauen

```bash

# Repo klonen
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# Mit CUDA bauen
make LLAMA_CUDA=1

# Oder mit CMake
mkdir build && cd build
cmake .. -DLLAMA_CUDA=ON
cmake --build . --config Release
```

## Modelle herunterladen

```bash

# Llama 3.1 8B
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Mistral 7B
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf

# Mixtral 8x7B
wget https://huggingface.co/bartowski/Mixtral-8x7B-Instruct-v0.1-GGUF/resolve/main/Mixtral-8x7B-Instruct-v0.1-Q4_K_M.gguf

# Phi-2
wget https://huggingface.co/bartowski/Phi-4-GGUF/resolve/main/Phi-4-Q4_K_M.gguf

# CodeLlama 7B
wget https://huggingface.co/bartowski/CodeLlama-7B-Instruct-GGUF/resolve/main/CodeLlama-7B-Instruct-Q4_K_M.gguf
```

## Serveroptionen

### Basiser Server

```bash
./llama-server \
    -m model.gguf \
    --host 0.0.0.0 \
    --port 8080
```

### Vollständiges GPU-Offload

```bash
./llama-server \
    -m model.gguf \
    --host 0.0.0.0 \
    --port 8080 \
    -ngl 99 \           # GPU-Schichten (99 = alle)
    -c 4096 \           # Kontextgröße
    -t 8 \              # CPU-Threads
    --parallel 4        # Gleichzeitige Anfragen
```

### Alle Optionen

```bash
./llama-server \
    -m model.gguf \           # Modelldatei
    --host 0.0.0.0 \          # Bind-Adresse
    --port 8080 \             # Port
    -ngl 35 \                 # GPU-Schichten
    -c 4096 \                 # Kontextgröße
    -t 8 \                    # Threads
    -b 512 \                  # Batch-Größe
    --parallel 4 \            # Parallele Anfragen
    --mlock \                 # Speicher sperren
    --no-mmap \               # mmap deaktivieren
    --cont-batching \         # Kontinuierliches Batching
    --flash-attn \            # Flash-Attention
    --metrics                 # Metriken-Endpunkt aktivieren
```

## API-Nutzung

### Chat-Completions (OpenAI-kompatibel)

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="nicht benötigt"
)

response = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is machine learning?"}
    ],
    temperature=0.7,
    max_tokens=500
)

print(response.choices[0].message.content)
```

### Streaming

```python
stream = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[{"role": "user", "content": "Write a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

### Textvervollständigung

```python
response = client.completions.create(
    model="llama-3.1-8b",
    prompt="The future of AI is",
    max_tokens=100,
    temperature=0.8
)

print(response.choices[0].text)
```

### Embeddings

```python
response = client.embeddings.create(
    model="llama-3.1-8b",
    input="Hello, world!"
)

print(f"Embedding: {response.data[0].embedding[:5]}...")
```

## cURL-Beispiele

### Chat

```bash
curl http://localhost:8080/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "llama-3.1-8b",
        "messages": [
            {"role": "user", "content": "Hello!"}
        ]
    }'
```

### Completion

```bash
curl http://localhost:8080/completion \
    -H "Content-Type: application/json" \
    -d '{
        "prompt": "Building a website requires",
        "n_predict": 128,
        "temperature": 0.7
    }'
```

### Health-Check

```bash
curl http://localhost:8080/health
```

### Metriken

```bash
curl http://localhost:8080/metrics
```

## Multi-GPU

```bash

# Auf mehrere GPUs aufteilen
./llama-server \
    -m model.gguf \
    -ngl 99 \
    --tensor-split 0.5,0.5 \  # Aufteilung zwischen 2 GPUs
    --main-gpu 0              # Primäre GPU
```

## Speicheroptimierung

### Für begrenzten VRAM

```bash

# Teilweises Offload
./llama-server -m model.gguf -ngl 20 -c 2048

# Kleinere Quantisierung verwenden

# Laden Sie stattdessen Q2_K oder Q3_K anstelle von Q4_K herunter
```

### Für maximale Geschwindigkeit

```bash
./llama-server \
    -m model.gguf \
    -ngl 99 \
    --flash-attn \
    --cont-batching \
    --parallel 8 \
    -b 1024
```

## Modellspezifische Vorlagen

### Llama 2 Chat

```bash
./llama-server -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
    --chat-template llama2
```

### Mistral Instruct

```bash
./llama-server -m mistral-7b-instruct.gguf \
    --chat-template mistral
```

### ChatML (Viele Modelle)

```bash
./llama-server -m model.gguf \
    --chat-template chatml
```

## Python-Server-Wrapper

```python
import subprocess
import requests
import time

class LlamaCppServer:
    def __init__(self, model_path, port=8080, gpu_layers=35):
        self.port = port
        self.process = subprocess.Popen([
            "./llama-server",
            "-m", model_path,
            "--host", "0.0.0.0",
            "--port", str(port),
            "-ngl", str(gpu_layers),
            "-c", "4096"
        ])
        self._wait_for_ready()

    def _wait_for_ready(self, timeout=60):
        start = time.time()
        while time.time() - start < timeout:
            try:
                r = requests.get(f"http://localhost:{self.port}/health")
                if r.status_code == 200:
                    return
            except:
                pass
            time.sleep(1)
        raise TimeoutError("Server didn't start")

    def chat(self, messages, **kwargs):
        response = requests.post(
            f"http://localhost:{self.port}/v1/chat/completions",
            json={"messages": messages, **kwargs}
        )
        return response.json()

    def stop(self):
        self.process.terminate()

# Verwendung
server = LlamaCppServer("llama-3.1-8b.gguf")
result = server.chat([{"role": "user", "content": "Hello!"}])
print(result["choices"][0]["message"]["content"])
server.stop()
```

## Benchmarking

```bash

# Eingebautes Benchmark
./llama-bench -m model.gguf -ngl 99

# Ausgabe beinhaltet:

# - Tokens pro Sekunde

# - Speicherverbrauch

# - Ladezeit
```

## Leistungsvergleich

| Modell       | GPU      | Quantisierung | Tokens/sec |
| ------------ | -------- | ------------- | ---------- |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M      | \~100      |
| Llama 3.1 8B | RTX 4090 | Q4\_K\_M      | \~150      |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M      | \~60       |
| Mistral 7B   | RTX 3090 | Q4\_K\_M      | \~110      |
| Mixtral 8x7B | A100     | Q4\_K\_M      | \~50       |

## Fehlerbehebung

### CUDA nicht erkannt

```bash

# Mit CUDA neu bauen
make clean
make LLAMA_CUDA=1

# CUDA prüfen
nvidia-smi
```

### Kein Speicher mehr

```bash

# GPU-Schichten reduzieren
-ngl 20  # Statt 99

# Kontext reduzieren
-c 2048  # Statt 4096

# Kleinere Quantisierung verwenden

# Q4_K_S statt Q4_K_M
```

### Langsame Generierung

```bash

# Batch-Größe erhöhen
-b 1024

# Flash-Attention aktivieren
--flash-attn

# Kontinuierliches Batching aktivieren
--cont-batching
```

## Produktions-Setup

### Systemd-Dienst

```ini

# /etc/systemd/system/llama.service
[Unit]
Description=Llama.cpp Server
After=network.target

[Service]
Type=simple
ExecStart=/opt/llama.cpp/llama-server -m /models/model.gguf -ngl 99 --host 0.0.0.0 --port 8080
Restart=always

[Install]
WantedBy=multi-user.target
```

### Mit nginx

```nginx
upstream llama {
    server localhost:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://llama;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
```

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

* vLLM-Inferenz - Höherer Durchsatz
* [ExLlamaV2](https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/exllamav2-fast) - Schnellere Inferenz
* [Text Generation WebUI](https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/text-generation-webui) - Weboberfläche
