> 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ühren Sie Microsofts Phi-4 aus - ein kleines, aber leistungsstarkes Sprachmodell.

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

Phi-4 von Microsoft bietet:

* 14B Parameter mit ausgezeichneter Leistung
* Übertrifft größere Modelle in Benchmarks
* Starke Schlussfolgerungs- und Mathematikfähigkeiten
* Effiziente Inferenz

## Modellvarianten

| Modell         | Parameter        | VRAM | Spezialgebiet      |
| -------------- | ---------------- | ---- | ------------------ |
| Phi-4          | 14B              | 16GB | Allgemein          |
| Phi-3.5-mini   | 3,8B             | 4GB  | Leichtgewichtig    |
| Phi-3.5-MoE    | 42B (6,6B aktiv) | 16GB | Mixture of Experts |
| Phi-3.5-vision | 4,2B             | 6GB  | Vision             |

## Schnelle Bereitstellung

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

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

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

# 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": "You are a helpful AI assistant."},
    {"role": "user", "content": "Explain the difference between TCP and 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 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|>\nDescribe this diagram in 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 Schlussfolgern

```python
messages = [
    {"role": "user", "content": """
Löse Schritt für Schritt:
Ein Bauer hat Hühner und Kaninchen.
Gesamtanzahl der Köpfe: 35
Gesamtanzahl der Beine: 94
Wie viele von jedem Tier?
"""}
]

# Phi-4 glänzt bei schrittweisem Denken
```

## Codegenerierung

```python
messages = [
    {"role": "user", "content": """
Schreiben Sie eine Python-Implementierung eines binären Suchbaums mit:
- Einfügen
- Suche
- Löschen
- Inorder-Traversierung
Fügen Sie Typangaben 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="You are a helpful assistant.", label="System"),
        gr.Slider(0.1, 1.5, value=0.7, label="Temperature")
    ],
    title="Phi-4 Chat"
)

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

## Leistung

| Modell        | GPU      | Tokens/sec |
| ------------- | -------- | ---------- |
| 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 oder übertrifft deutlich größere Modelle*

## Fehlerbehebung

### "trust\_remote\_code" Fehler

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

### Wiederholende Ausgaben

* Niedrigere Temperatur (0,3-0,6)
* Fügen Sie repetition\_penalty=1.1 hinzu
* Verwenden Sie die richtige Chat-Vorlage

### Speicherprobleme

* Phi-4 ist effizient, benötigt aber trotzdem \~8 GB für 14B
* Verwenden Sie bei Bedarf 4-Bit-Quantisierung
* Reduzieren Sie die Kontextlänge

### Falsches Ausgabeformat

* Verwenden Sie `apply_chat_template()` für richtige Formatierung
* Überprüfen Sie, ob Sie die Instruct-Version verwenden, nicht die Basisversion

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

## Anwendungsfälle

* Mathematik-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:

```
GET https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/phi4.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.
