> 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

{% hint style="info" %}
**Neuere Version verfügbar!** Google hat veröffentlicht [**Gemma 3**](/guides/guides_v2-de/sprachmodelle/gemma3.md) im März 2025 — das 27B-Modell übertrifft Llama 3.1 405B und fügt native Multimodal-Unterstützung hinzu. Ziehen Sie ein Upgrade in Betracht.
{% 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 über [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% 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 Gemma 2?

Gemma 2 von Google bietet:

* Modelle von 2B bis 27B Parametern
* Ausgezeichnete Leistung pro Größe
* Starke Befolgung von Anweisungen
* Effiziente Architektur

## Modellvarianten

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

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
```

**Ports:**

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

**Befehl:**

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

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

## 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äre, 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"

# Verwenden Sie 4-Bit, um in 24GB 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ähl mir eine Kurzgeschichte"}],
    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.",
    "Wie schnell ist das Licht?"
]

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/sec |
| ------------------- | -------- | ---------- |
| 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 out of memory**
{% endhint %}

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

### Langsame Generierung

* Verwenden Sie vLLM für Produktionsbereitstellung
* Aktivieren Sie Flash Attention
* Probieren Sie das 9B-Modell für schnellere Inferenz

### Probleme mit der Ausgabequalität

* Verwenden Sie die instruktionstuning-Version (`-it` Suffix)
* Temperatur anpassen (0,7–0,9 empfohlen)
* Fügen Sie einen Systemprompt für Kontext hinzu

### Tokenizer-Warnungen

* Aktualisieren Sie transformers auf die neueste Version
* Verwenden Sie `padding_side="left"` für Batch-Inferenz

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

* Llama 3.2 - Metas Modell
* Qwen2.5 - Alibabas Modell
* vLLM-Inferenz - Produktionseinsatz


---

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