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

# Phi-4

Führe Microsofts kleines Sprachmodell Phi-4 auf Clore.ai-GPUs aus

Starte Microsofts Phi-4 – ein kleines, aber leistungsstarkes Sprachmodell.

{% 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 Phi-4?

Phi-4 von Microsoft bietet:

* 14B Parameter mit hervorragender Leistung
* Übertrifft größere Modelle in Benchmarks
* Starkes Schlussfolgern und Mathematik
* Effiziente Inferenz

## Modellvarianten

| Modell         | Parameter        | VRAM  | Spezialgebiet    |
| -------------- | ---------------- | ----- | ---------------- |
| Phi-4          | 14B              | 16 GB | Allgemein        |
| Phi-3.5-mini   | 3.8B             | 4 GB  | Leichtgewichtig  |
| Phi-3.5-MoE    | 42B (6.6B aktiv) | 16 GB | Expertenmischung |
| Phi-3.5-vision | 4.2B             | 6 GB  | Vision           |

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

```bash
pip install transformers accelerate torch && \
python phi4_server.py
```

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

# Phi-4 ausführen
ollama run phi4

# Phi-3.5 mini (schneller)
ollama run phi3.5

# Phi-3.5 Vision
ollama run phi3.5-vision
```

## Installation

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

## Grundlegende Verwendung

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

model_id = "microsoft/Phi-4"

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

messages = [
    {"role": "system", "content": "Du bist ein hilfreicher KI-Assistent."},
    {"role": "user", "content": "Erkläre den Unterschied zwischen TCP und UDP."}
]

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

## Phi-3.5-Vision

Für das Bildverständnis:

```python
from transformers import AutoModelForCausalLM, AutoProcessor
from PIL import Image
import torch

model_id = "microsoft/Phi-3.5-vision-instruct"

processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True
)

image = Image.open("diagram.png")

messages = [
    {"role": "user", "content": "<|image_1|>\nBeschreibe dieses Diagramm im Detail."}
]

prompt = processor.tokenizer.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)

inputs = processor(prompt, [image], return_tensors="pt").to("cuda")

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

response = processor.decode(outputs[0], skip_special_tokens=True)
print(response)
```

## Mathematik und logisches Denken

```python
messages = [
    {"role": "user", "content": """
Schritt für Schritt lösen:
Ein Bauer hat Hühner und Kaninchen.
Gesamtzahl der Köpfe: 35
Gesamtzahl der Beine: 94
Wie viele von jeder Tierart?
"""}
]

# Phi-4 überzeugt beim schrittweisen logischen Denken
```

## Codegenerierung

```python
messages = [
    {"role": "user", "content": """
Schreibe eine Python-Implementierung eines binären Suchbaums mit:
- Einfügen
- Suchen
- Löschen
- In-Order-Durchlauf
Füge Typ-Hinweise und Docstrings hinzu.
"""}
]
```

## Quantisierte Inferenz

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

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Phi-4",
    quantization_config=quantization_config,
    device_map="auto",
    trust_remote_code=True
)
```

## Gradio-Oberfläche

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

model_id = "microsoft/Phi-4"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True
)

def chat(message, history, system_prompt, temperature):
    messages = [{"role": "system", "content": system_prompt}]
    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").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.Textbox(value="Du bist ein hilfreicher Assistent.", label="System"),
        gr.Slider(0.1, 1.5, value=0.7, label="Temperatur")
    ],
    title="Phi-4-Chat"
)

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

## Leistung

| Modell        | GPU      | Tokens/Sek. |
| ------------- | -------- | ----------- |
| Phi-3.5-mini  | RTX 3060 | \~100       |
| Phi-3.5-mini  | RTX 4090 | \~150       |
| Phi-4         | RTX 4090 | \~60        |
| Phi-4         | A100     | \~90        |
| Phi-4 (4-Bit) | RTX 3090 | \~40        |

## Benchmarks

| Modell        | MMLU  | HumanEval | GSM8K |
| ------------- | ----- | --------- | ----- |
| Phi-4         | 84.8% | 82.6%     | 94.6% |
| GPT-4-Turbo   | 86.4% | 85.4%     | 94.2% |
| Llama-3.1-70B | 83.6% | 80.5%     | 92.1% |

*Phi-4 erreicht das Niveau deutlich größerer Modelle oder übertrifft sie*

## Fehlerbehebung

### "trust\_remote\_code"-Fehler

* Fügen Sie `trust_remote_code=True` auf `from_pretrained()`
* Dies ist für Phi-Modelle erforderlich

### Wiederholte Ausgaben

* Niedrigere Temperatur (0,3–0,6)
* Füge repetition\_penalty=1.1 hinzu
* Verwende die richtige Chat-Vorlage

### Speicherprobleme

* Phi-4 ist effizient, benötigt aber für 14B trotzdem etwa 8 GB
* Nutze bei Bedarf 4-Bit-Quantisierung
* Reduziere die Kontextlänge

### Falsches Ausgabeformat

* Verwende `apply_chat_template()` für die richtige Formatierung
* Prüfe, ob du die Instruct-Version und nicht die Basisversion verwendest

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

## Anwendungsfälle

* Mathe-Nachhilfe
* Code-Unterstützung
* Dokumentenanalyse (Vision)
* Effiziente Edge-Bereitstellung
* Kosteneffiziente Inferenz

## Nächste Schritte

* Qwen2.5 - alternatives Modell
* Gemma 2 - Googles Modell
* Llama 3.2 - Metas Modell


---

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