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

# Gemma 2

Führe Googles Gemma-2-Modelle effizient auf Clore.ai-GPUs aus

{% hint style="info" %}
**Neuere Version verfügbar!** Von Google veröffentlicht [**Gemma 3**](/guides/guides_v2-de/sprachmodelle/gemma3.md) im März 2025 — das 27B-Modell schlägt Llama 3.1 405B und bietet native multimodale Unterstützung. Erwägen Sie ein Upgrade.
{% endhint %}

Führen Sie Googles Gemma-2-Modelle für effiziente Inferenz aus.

{% 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 %}

## 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 Gemma 2?

Gemma 2 von Google bietet:

* Modelle mit 2B bis 27B Parametern
* Hervorragende Leistung pro Größe
* Starkes Befolgen von Anweisungen
* Effiziente Architektur

## Modellvarianten

| Modell      | Parameter | VRAM  | Kontext |
| ----------- | --------- | ----- | ------- |
| Gemma-2-2B  | 2B        | 3GB   | 8K      |
| Gemma-2-9B  | 9B        | 12 GB | 8K      |
| Gemma-2-27B | 27B       | 32 GB | 8K      |

## Schnell bereitstellen

**Docker-Image:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**Ports:**

```
22/tcp
8000/http
```

**Befehl:**

```bash
pip install vllm && \\
vllm serve google/gemma-2-9b-it --port 8000
```

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

## Verwendung von Ollama

```bash

# Gemma 2 ausführen
ollama run gemma2

# Spezifische Größen
ollama run gemma2:2b
ollama run gemma2:9b
ollama run gemma2:27b
```

## Installation

```bash
pip install transformers accelerate torch
```

## Grundlegende Verwendung

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "google/gemma-2-9b-it"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "Erklären Sie, wie neuronale Netze lernen."}
]

inputs = tokenizer.apply_chat_template(
    messages,
    return_tensors="pt",
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=512,
    temperature=0.7,
    do_sample=True
)

response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
print(response)
```

## Gemma 2 2B (Leichtgewichtig)

Für Edge-/Mobile-Bereitstellung:

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "google/gemma-2-2b-it"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

# Schnelle Inferenz für einfache Aufgaben
messages = [{"role": "user", "content": "Fasse in einem Satz zusammen: KI verändert Branchen."}]
```

## Gemma 2 27B (Beste Qualität)

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch

model_id = "google/gemma-2-27b-it"

# 4-Bit verwenden, um in 24 GB VRAM zu passen
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    quantization_config=quantization_config,
    device_map="auto"
)
```

## vLLM-Server

```bash
vllm serve google/gemma-2-9b-it \\
    --port 8000 \\
    --dtype bfloat16 \\
    --max-model-len 8192
```

### OpenAI-kompatible API

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

response = client.chat.completions.create(
    model="google/gemma-2-9b-it",
    messages=[
        {"role": "user", "content": "Schreibe ein Haiku über Programmierung"}
    ],
    temperature=0.8
)

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

## Streaming

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

stream = client.chat.completions.create(
    model="google/gemma-2-9b-it",
    messages=[{"role": "user", "content": "Erzählen Sie mir eine kurze Geschichte"}],
    stream=True
)

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

## Gradio-Oberfläche

```python
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

def chat(message, history, temperature):
    messages = []
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to("cuda")
    outputs = model.generate(inputs, max_new_tokens=512, temperature=temperature, do_sample=True)

    return tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[gr.Slider(0.1, 1.5, value=0.7, label="Temperatur")],
    title="Gemma 2 Chat"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## Batch-Verarbeitung

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

prompts = [
    "Erkläre die Schwerkraft in einem Satz.",
    "Was ist Photosynthese?",
    "Definiere maschinelles Lernen.",
    "Was ist die Lichtgeschwindigkeit?"
]

messages_batch = [[{"role": "user", "content": p}] for p in prompts]

inputs = tokenizer.apply_chat_template(
    messages_batch,
    return_tensors="pt",
    padding=True,
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(inputs, max_new_tokens=128, pad_token_id=tokenizer.pad_token_id)

for i, output in enumerate(outputs):
    response = tokenizer.decode(output, skip_special_tokens=True)
    print(f"Q: {prompts[i]}")
    print(f"A: {response.split('<start_of_turn>model')[-1].strip()}\n")
```

## Leistung

| Modell              | GPU      | Tokens/Sek. |
| ------------------- | -------- | ----------- |
| Gemma-2-2B          | RTX 3060 | \~100       |
| Gemma-2-9B          | RTX 3090 | \~60        |
| Gemma-2-9B          | RTX 4090 | \~85        |
| Gemma-2-27B         | A100     | \~45        |
| Gemma-2-27B (4-Bit) | RTX 4090 | \~30        |

## Vergleich

| Modell       | MMLU  | Qualität  | Geschwindigkeit |
| ------------ | ----- | --------- | --------------- |
| Gemma-2-9B   | 71.3% | Großartig | Schnell         |
| Llama-3.1-8B | 69.4% | Gut       | Schnell         |
| Mistral-7B   | 62.5% | Gut       | Schnell         |

## Fehlerbehebung

{% hint style="danger" %}
**CUDA-Speicher erschöpft**
{% endhint %}

für 27B - 4-Bit-Quantisierung mit BitsAndBytesConfig verwenden - \`max\_new\_tokens\` reduzieren - GPU-Cache leeren: \`torch.cuda.empty\_cache()\`

### Langsame Generierung

* Verwenden Sie vLLM für den Produktionseinsatz
* Flash Attention aktivieren
* Probieren Sie das 9B-Modell für schnellere Inferenz

### Probleme mit der Ausgabequalität

* Verwenden Sie die auf Anweisungen abgestimmte Version (`-it` Suffix)
* Temperatur anpassen (0,7–0,9 empfohlen)
* System-Prompt für Kontext hinzufügen

### Tokenizer-Warnungen

* Transformers auf die neueste Version aktualisieren
* Verwende `padding_side="left"` für Batch-Inferenz

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

* Llama 3.2 - Metas Modell
* Qwen2.5 - Alibabas Modell
* vLLM Inference - Produktionsbereitstellung


---

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