> 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/sprachmodelle/llamacpp-server.md).

# Llama.cpp Server

Effiziente LLM-Inferenz mit llama.cpp-Server auf Clore.ai-GPUs

LLMs effizient mit dem llama.cpp-Server auf der GPU ausführen.

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

## Serveranforderungen

| Parameter | Minimum       | Empfohlen |
| --------- | ------------- | --------- |
| RAM       | 8 GB          | 16GB+     |
| VRAM      | 6 GB          | 8 GB+     |
| Netzwerk  | 200Mbps       | 500Mbps+  |
| Startzeit | \~2-5 Minuten | -         |

{% hint style="info" %}
Llama.cpp ist durch GGUF-Quantisierung speichereffizient. 7B-Modelle können auf 6-8 GB VRAM laufen.
{% endhint %}

## Mieten auf CLORE.AI

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

### Greife auf deinen Server zu

* Verbindungsdetails finden in **Meine Bestellungen**
* Web-Oberflächen: Verwende 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
* Unterstützung für mehrere Benutzer

## Quantisierungsstufen

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

## Schnell bereitstellen

**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
```

## Auf deinen Dienst zugreifen

Nach der Bereitstellung findest du deine `http_pub` URL in **Meine Bestellungen**:

1. Gehe zu **Meine Bestellungen** Seite
2. Klicke auf deine Bestellung
3. Finde die `http_pub` URL (z. B. `abc123.clorecloud.net`)

Verwende `https://YOUR_HTTP_PUB_URL` anstelle von `localhost` in den folgenden Beispielen.

### Prüfen, ob es funktioniert

```bash
# Status 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

### Standard-Endpunkte

| Endpunkt               | Methode | Beschreibung                              |
| ---------------------- | ------- | ----------------------------------------- |
| `/health`              | GET     | Statusprüfung                             |
| `/v1/models`           | GET     | Modelle auflisten                         |
| `/v1/chat/completions` | POST    | Chat (OpenAI-kompatibel)                  |
| `/v1/completions`      | POST    | Textvervollständigung (OpenAI-kompatibel) |
| `/v1/embeddings`       | POST    | Embeddings generieren                     |
| `/completion`          | POST    | Nativer Vervollständigungs-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": "Hallo Welt"}'
```

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 dem Quellcode 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

### Basis-Server

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

### Vollständiges GPU-Offloading

```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 \\                  # Batchgröße
    --parallel 4 \\            # Parallele Anfragen
    --mlock \\                 # Speicher sperren
    --no-mmap \\               # mmap deaktivieren
    --cont-batching \\         # Kontinuierliches Batching
    --flash-attn \\            # Flash-Attention
    --metrics                 # Metrik-Endpunkt aktivieren
```

## API-Nutzung

### Chat-Vervollständigungen (OpenAI-kompatibel)

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed"
)

response = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[
        {"role": "system", "content": "Du bist ein hilfreicher Assistent."},
        {"role": "user", "content": "Was ist maschinelles Lernen?"}
    ],
    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": "Schreibe eine Geschichte"}],
    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="Die Zukunft der KI ist",
    max_tokens=100,
    temperature=0.8
)

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

### Embeddings

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

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": "Hallo!"}
        ]
    }'
```

### Vervollständigung

```bash
curl http://localhost:8080/completion \\
    -H "Content-Type: application/json" \\
    -d '{
        "prompt": "Das Erstellen einer Website erfordert",
        "n_predict": 128,
        "temperature": 0.7
    }'
```

### Statusprüfung

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

### Metriken

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

## Multi-GPU

```bash

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

## Speicheroptimierung

### Bei begrenztem VRAM

```bash

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

# Kleinere Quantisierung verwenden

# Q2_K oder Q3_K statt Q4_K herunterladen
```

### 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("Der Server wurde nicht gestartet")

    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": "Hallo!"}])
print(result["choices"][0]["message"]["content"] )
server.stop()
```

## Benchmarking

```bash

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

# Ausgabe enthält:

# - Tokens pro Sekunde

# - Speichernutzung

# - Ladezeit
```

## Leistungsvergleich

| Modell       | GPU      | Quantisierung | Tokens/Sek. |
| ------------ | -------- | ------------- | ----------- |
| 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 kompilieren
make clean
make LLAMA_CUDA=1

# CUDA prüfen
nvidia-smi
```

### Speicher erschöpft

```bash

# GPU-Layer reduzieren
-ngl 20  # Statt 99

# Kontext reduzieren
-c 2048  # Statt 4096

# Kleinere Quantisierung verwenden

# Q4_K_S statt Q4_K_M
```

### Langsame Generierung

```bash

# Batchgröß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 "";
    }
}
```

## Kostenschätzung

Übliche CLORE.AI-Marktplatzpreise (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           |

*Die Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI-Marktplatz*](https://clore.ai/marketplace) *für aktuelle Preise.*

**Geld sparen:**

* Nutzen Sie den **Spot** Markt für unterbrechbare Arbeit — etwa ein Drittel der Server bietet Spot-Preise unter dem On-Demand-Preis (Median ca. 13 % Rabatt), der Rest ist gleichauf
* Bezahlen Sie mit **CLORE** Tokens
* Vergleichen Sie Preise zwischen verschiedenen Anbietern

## Nächste Schritte

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


---

# 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, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/llamacpp-server.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
